<template>
	<view class="custome-recommendation">
		<view class="page-header">
			<view class="status-bar"></view>
			<view class="header-title">新阳光广场</view>
			<view class="header-content">
				<view class="user-info">
					<view class="avatar-section">
						<view class="avatar">
							<text class="avatar-text">{{ $userInfo.nickName.charAt(0) }}</text>
						</view>
					</view>
					<view class="user-details">
						<text class="username">{{ $userInfo.nickName }}</text>
						<text class="role">{{ $userInfo.agency }}</text>
					</view>
				</view>
				<view class="stats">
					<view class="stat-item">
						<text class="stat-value">{{ myTotal }}</text>
						<text class="stat-label">今日推荐</text>
					</view>
				</view>
			</view>
		</view>




		<!-- 快捷操作 -->
		<view class="quick-actions">
			<view class="action-item" @click="addNewCustomer">
				<view class="action-icon add">
					<image src="@/static/imgs/add.png"></image>
				</view>
				<text class="action-text">新建客户</text>
			</view>
			<!-- <view class="action-item" @click="viewPerformance">
				<view class="action-icon performance">📊</view>
				<text class="action-text">业绩统计</text>
			</view> -->
			<view class="action-item" @click="linkMyCustomer">
				<view class="action-icon properties">
					<image src="@/static/imgs/customer-ac.png"></image>
				</view>
				<text class="action-text">我的客户</text>
			</view>
			<view class="action-item" @click="loginOut">
				<view class="action-icon properties">
					<image src="@/static/imgs/loginOut.png"></image>
				</view>
				<text class="action-text">退出登录</text>
			</view>
		</view>
		<!-- 今日推荐客户 -->
		<view class="section">
			<view class="section-header">
				<view style="flex:1">
					<text class="section-title">当日未报备</text>
					<uni-badge class="uni-badge-left-margin" :text="currentCustomers.length" />
					<!-- <text class="section-badge">{{ currentCustomers.length }}</text> -->
				</view>
				<text class="see-all" @click="viewMyHistory(2)">查看全部</text>
			</view>

			<view class="customer-list" v-if="currentCustomers.length > 0">
				<view class="customer-card" v-for="customer in currentCustomers" :key="customer._id"
					@click="viewCustomerDetail(customer)">
					<view class="customer-header">
						<view class="customer-info">
							<text class="customer-name">{{ customer.customerName }}</text>
							<text class="customer-phone">{{ $formatPhone(customer.phone) }}</text>
						</view>
						<view class="customer-tag" :class="customer.priority">
							{{ getPriorityText(customer.priority) }}
						</view>
					</view>

					<view class="customer-details" v-if="customer.interestedType || customer.budget">
						<view class="detail-item" v-if="customer.interestedType">
							<text class="detail-label">关注户型</text>
							<text class="detail-value">{{ customer.interestedType }}</text>
						</view>
						<view class="detail-item" v-if="customer.budget">
							<text class="detail-label">预算范围</text>
							<text class="detail-value">{{ formatBudget(customer.budget) }}</text>
						</view>
					</view>

					<view class="customer-actions">
						<text class="visit-time">
							<template v-if="customer.scheduleDateTime">
								上次报备: {{$formatTime( customer.scheduleDateTime) }}
							</template>
						</text>
						<view class="action-buttons">
							<!-- <button class="btn-small primary" @tap.stop="getQrCode(customer)">二维码</button> -->
							<!-- <button class="btn-small primary" @tap.stop="contactCustomer(customer)">联系</button> -->
							<button class="btn-small secondary" @tap.stop="scheduleVisit(customer)">报备</button>
						</view>
					</view>
				</view>
			</view>

			<view class="empty-state" v-else>
				<text class="empty-text">暂无正在接待的客户</text>
				<button class="empty-btn" @click="addNewCustomer">添加客户</button>
			</view>
		</view>


		<view class="section" v-if="myCustomers.length">
			<view class="section-header">
				<view style="flex:1">
					<text class="section-title">当日报备</text>
					<uni-badge class="uni-badge-left-margin" :text="myTotal" />
				</view>
				<text class="see-all" @click="viewMyHistory(1)">查看全部</text>
			</view>

			<view class="customer-list" v-if="myCustomers.length > 0">
				<view class="customer-card" v-for="customer in myCustomers" :key="customer._id"
					@click="viewCustomerDetail(customer)">
					<view class="customer-header">
						<view class="customer-info">
							<text class="customer-name">{{ customer.customerName }}</text>
							<text class="customer-phone">{{ $formatPhone(customer.phone) }}</text>
						</view>
						<view class="customer-tag" :class="customer.priority">
							{{ getPriorityText(customer.priority) }}
						</view>
					</view>
					<view class="customer-details" v-if="customer.interestedType || customer.budget">
						<view class="detail-item" v-if="customer.interestedType">
							<text class="detail-label">关注户型</text>
							<text class="detail-value">{{ customer.interestedType }}</text>
						</view>
						<view class="detail-item" v-if="customer.budget">
							<text class="detail-label">预算范围</text>
							<text class="detail-value">{{ formatBudget(customer.budget) }}</text>
						</view>
					</view>

					<view class="customer-actions">
						<text class="visit-time">
							<template v-if="customer.scheduleDateTime">
								上次报备: {{$formatTime( customer.scheduleDateTime) }}
							</template>
						</text>
						<view class="action-buttons">
							<button class="btn-small primary" @tap.stop="contactCustomer(customer)">联系</button>
							<button class="btn-small btn-primary" v-if="customer.scheduleNo"
								@tap.stop="scheduleVisit(customer)">报备码</button>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 成功提示 -->
		<uni-popup ref="successPopup" type="dialog">
			<uni-popup-dialog ref="inputClose" mode="input" title="输入查询" :beforeClose="true" @close="closeFun"
				placeholder="请输入手机号码查询" @confirm="dialogInputConfirm"></uni-popup-dialog>
		</uni-popup>


		<uni-popup ref="qrcode">
			<view class="qr-container">
				<view class="qrcode-area">
					<canvas canvas-id="myQrcode" style="width: 250px; height: 250px;"></canvas>
				</view>
				<view class="action-area">
					<button class="btn-mid btn-primary" @click="saveQRCode">保存二维码</button>
				</view>
			</view>
		</uni-popup>


		<!-- 
		// 今天报备客户 【无效】, 15 min
		// 有效客户     【历史，60+】 -->

	</view>
</template>

<script>
	import UQRCode from 'uqrcodejs';
	export default {
		name: 'CustomerRecommendation',
		data() {
			return {
				currentCustomer: {},
				currentCustomers: [],
				today: '',
				myCustomers: [],
				historyCustomers: [],
				myTotal: 0
			}
		},
		onShow() {
			let curTime = this.$formatTime(new Date())
			this.loadCustomers()
			// this.loadTodayCustomer()
			this.historyCustom()
		},
		methods: {
			// 加载客户数据
			async loadCustomers() {
				// 从middleman-advisor-customers查询当天未报备的客户
				const res = await this.$cloudOBjAjax('middleman-advisor-customers', 'getCustomerList', {
					middlemanId: this.$userInfo._id,
					isSchedule: 0, // 未报备
					pageSize: 100
				});

				if (res && res.list) {
					this.currentCustomers = res.list.map(customer => {
						return {
							...customer,
						};
					});
				}
			},

			async loadTodayCustomer() {
				let time = this.$formatYear(new Date())
				let res = await this.$cloudOBjAjax('suuny-custom', 'getZJCustomer', {
					pageSize: 1,
					schedule_time: time,
					isSchedule: 1,
				})
				this.today = res.total
				console.log(res)
				// this.currentCustomers = res.list
			},

			// 今日报备
			async historyCustom() {
				let time = this.$formatYear(new Date())
				let res = await this.$cloudOBjAjax('middleman-advisor-customers', 'getCustomerList', {
					schedule_time: time,
					middlemanId: this.$userInfo._id,
					pageNo:1,
					pageSize:3,
				})
				this.myCustomers = res.list
				this.myTotal = res.total
				console.log(res)
				// this.currentCustomers = res.list
			},

			linkMyCustomer() {
				uni.navigateTo({
					url: `/pages/mid/list`
				})
			},


			// 查看客户详情
			viewCustomerDetail(customer) {
				uni.navigateTo({
					url: `/pages/mid/detail?id=${customer._id}`
				})
			},

			// 联系客户
			contactCustomer(customer) {
				uni.makePhoneCall({
					phoneNumber: customer.phone
				})
			},

			// 预约访问
			async scheduleVisit(customer) {
				uni.setStorageSync('customer',customer)
				uni.navigateTo({
					url:"/pages/customer/sheduleVisit"
				})
				
			},

			// 添加新客户
			addNewCustomer() {
				this.$refs.successPopup.open()
			},
			closeFun() {
				this.$refs.successPopup.close()
			},
			async dialogInputConfirm(value) {
		
				let isTest2 = !/^(1\d{6}|1[3-9]\d{9})$/.test(value)
				if (isTest2) {
				    return this.$simpleToast('电话号码错误')
				}
				

				this.$cloudOBjAjax('middleman-advisor-customers', 'checkCustomerExists', {
					phone: value,
					middlemanId: this.$userInfo._id
				}).catch(err => {
					this.$simpleToast(err.errMsg || '出错了,请联系管理员')
				}).then(res => {
					if (res.exists) {
						this.$simpleToast('该客户已经被注册了')
					} else {
						this.closeFun()
						uni.navigateTo({
							url: "/pages/customer/addByadvisor?phone=" + value
						})
					}

				}).catch(err => {
					this.$simpleToast(err.errMsg || '出错了,请联系管理员')
				})
			},

			// 查看全部历史
			viewAllHistory() {
				uni.navigateTo({
					url: '/pages/customer/list'
				})
			},
			viewMyHistory(type) {
				switch (type){
					case 2:
						uni.navigateTo({
							url: "/pages/mid/list?type=2"
						})
						break;
					case 1:
					uni.navigateTo({
						url: "/pages/mid/today"
					})
					break;
					default:
					uni.navigateTo({
						url: "/pages/mid/list"
					})
						break;
				}
				
			},

			// 获取头像文字
			getAvatarText(name) {
				if (!name) return '客'
				return name.length > 2 ? name.substring(name.length - 2) : name
			},

			// 获取优先级文本
			getPriorityText(priority) {
				const map = {
					'high': '高意向',
					'medium': '中意向',
					'low': '普通'
				}
				return map[priority] || '普通'
			},

			// 获取状态文本
			getStatusText(status) {
				const map = {
					'completed': '已成交',
					'lost': '已流失',
					'pending': '跟进中'
				}
				return map[status] || '未知'
			},
			loginOut() {
				uni.showModal({
					title: '确认退出',
					content: '确定要退出登录吗？',
					success: (res) => {
						if (res.confirm) {
							// 清除登录状态
							uni.removeStorageSync('userInfo')

							// 跳转到登录页
							uni.reLaunch({
								url: '/pages/login/login'
							})
						}
					}
				})
			},
			showQrcode(item) {
				this.$refs.qrcode.open()
				setTimeout(() => {
					const qrcode = new UQRCode();
					qrcode.data = item.scheduleNo;
					qrcode.size = 250;
					qrcode.margin = 15;
					qrcode.foregroundColor = '#000000';
					qrcode.backgroundColor = '#ffffff';
					qrcode.errorCorrectLevel = UQRCode.errorCorrectLevel.H;
					qrcode.make();
					const ctx = uni.createCanvasContext('myQrcode', this);
					qrcode.canvasContext = ctx;
					qrcode.draw();
				}, 100)
			},
			saveQRCode() {
				// 将canvas内容保存为图片
				uni.canvasToTempFilePath({
					canvasId: 'myQrcode',
					success: (res) => {
						// #ifdef H5
						const a = document.createElement('a');
						a.href = res.tempFilePath;
						a.download = 'qrcode.png'; // 设置下载文件名
						document.body.appendChild(a);
						a.click();
						document.body.removeChild(a);
						// #endif
						// #ifndef H5
						
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: () => {
								uni.showToast({
									title: '保存成功',
									icon: 'success'
								});
							},
							fail: (err) => {
								console.error('保存失败', err);
								uni.showToast({
									title: '保存失败',
									icon: 'none'
								});
							}
						});
						// #endif
					},
					fail() {
						console.log('fail')
					}
				}, this);
			}
		}
	}
</script>

<style scoped lang="scss">
	/* 当前客户列表 */
	.customer-list {
		display: flex;
		gap: 30rpx;
		white-space: nowrap;
		flex-direction: column;
	}

	.customer-card {
		min-width: 400rpx;
		background: #f8f9fa;
		border-radius: 16rpx;
		padding: 20rpx;
		border-left: 6rpx solid #667eea;
		margin-bottom: 10rpx;
	}

	.customer-header {
		display: flex;
		align-items: center;
		margin-bottom: 24rpx;
	}

	.customer-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin-right: 20rpx;
	}

	.customer-info {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.customer-name {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 8rpx;
	}

	.customer-phone {
		font-size: 22rpx;
		color: #666;
	}

	.customer-tag {
		padding: 8rpx 16rpx;
		border-radius: 12rpx;
		font-size: 20rpx;

		&.high {
			background: #ff4757;
			color: white;
		}

		&.medium {
			background: #ffa502;
			color: white;
		}

		&.low {
			background: #dfe4ea;
			color: #666;
		}
	}

	.customer-details {
		margin-bottom: 24rpx;
	}

	/* 悬浮按钮 */
	.floating-action {
		position: fixed;
		bottom: 40rpx;
		right: 40rpx;
		z-index: 999;
	}

	.fab-btn {
		background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
		color: white;
		padding: 20rpx 32rpx;
		border-radius: 50rpx;
		display: flex;
		align-items: center;
		gap: 12rpx;
		box-shadow: 0 8rpx 24rpx rgba(24, 144, 255, 0.3);
		border: none;
	}

	.fab-icon {
		font-size: 32rpx;
		font-weight: bold;
	}

	.fab-text {
		font-size: 28rpx;
	}

	/* 区域样式 */
	.section {
		background: white;
		margin: 20rpx 20rpx;
		border-radius: 20rpx;
		padding: 20rpx;
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
	}

	.section-header {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.section-title {
		font-size: 28rrpx;
		color: #333;
		margin-right: 16rpx;
	}
	
	.section-subtitle {
		font-size: 24rpx;
		color: #999;
		flex: 1;
	}
	
	.section-badge {
		background: #ff4757;
		color: white;
		padding: 4rpx 8rpx;
		border-radius: 20rpx;
		font-size: 20rpx;
	}
	
	.see-all {
		color: #999;
		font-size: 24rpx;
	}

	.detail-label {
		font-size: 24rpx;
		color: #666;
	}

	.detail-value {
		font-size: 24rpx;
		color: #333;
		font-weight: 500;
	}

	.customer-actions {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.visit-time {
		font-size: 22rpx;
		color: #999;
	}

	.action-buttons {
		display: flex;
		gap: 16rpx;
	}

	.btn-small {
		padding: 0 20rpx;
		border-radius: 4rpx;
		font-size: 22rpx;
		border: none;
		line-height: 40rpx;
		color: white;

		&.primary {
			background: #667eea;
			color: white;
		}

		&.secondary {
			background: #f1f2f6;
			color: #666;
		}
	}

	/* 空状态 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 80rpx 0;
	}

	.empty-icon {
		font-size: 80rpx;
		margin-bottom: 24rpx;
	}

	.empty-text {
		font-size: 28rpx;
		color: #999;
		margin-bottom: 40rpx;
	}

	.empty-btn {
		background: #667eea;
		color: white;
		border: none;
		border-radius: 10rpx;
		font-size: 26rpx;
		line-height: 60rpx;
		height:60rpx;
		padding:0 20rpx;
	}

	/* 历史客户列表 */
	.history-list {
		display: flex;
		flex-direction: column;
		gap: 30rpx;
		overflow-y: auto;
		max-height: calc(100vh - 700rpx);
		padding-bottom: 20rpx;
	}

	.history-item {
		display: flex;
		align-items: center;
		padding: 30rpx;
		background: #f8f9fa;
		border-radius: 16rpx;
	}

	.history-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin-right: 24rpx;
	}

	.history-content {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.history-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 8rpx;
	}

	.history-name {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
	}

	.history-status {
		padding: 6rpx 16rpx;
		border-radius: 12rpx;
		font-size: 20rpx;

		&.purchased {
			background: #2ed573;
			color: white;
		}

		&.negotiating {
			background: #ffa502;
			color: white;
		}

		&.not_purchased {
			background: #dfe4ea;
			color: #666;
		}
	}

	.history-phone {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 8rpx;
	}

	.history-date {
		font-size: 22rpx;
		color: #999;
	}

	.history-amount {
		text-align: right;
	}

	.amount {
		font-size: 28rpx;
		font-weight: bold;
		color: #ff4757;
	}

	/* 加载更多 */
	.load-more {
		text-align: center;
		padding: 30rpx;
		color: #667eea;
		font-size: 26rpx;
	}

	.avatar-section {
		margin-right: 24rpx;
	}




	.user-details {
		display: flex;
		flex-direction: column;
		position: relative;
	}

	.online-status {
		margin-top: 10rpx;
	}

	.status-btn {
		padding: 6rpx 20rpx;
		border-radius: 20rpx;
		font-size: 22rpx;
		border: none;
		color: white;

		// &.online {
		//   background: #4cd964;
		// }

		// &.offline {
		//   background: #ff4757;
		// }
	}

	.username {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 8rpx;
	}

	.role {
		font-size: 24rpx;
		opacity: 0.9;
	}

	.stats {
		display: flex;
		gap: 40rpx;
	}

	.stat-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.stat-value {
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 8rpx;
	}

	.stat-label {
		font-size: 22rpx;
		opacity: 0.9;
	}

	.quick-actions {
		display: flex;
		justify-content: space-around;
		background: white;
		margin: -160rpx 40rpx 30rpx;
		padding: 30rpx;
		border-radius: 20rpx;
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
	}

	.action-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.action-icon {
		image {
			width: 60rpx;
			height:60rpx;
		}
	}
	
	.action-text {
		font-size: 32rpx;
		color: #333;
	}

	.qr-container {
		padding: 20rpx;
		text-align: center;
		background-color: white;
		border-radius: 8rpx;

		.qrcode-area {
			margin: 40rpx 0;
		}

		button {
			margin: 10rpx;
		}
	}
</style>